package com.poseidon.cglibdemo.aop;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public abstract class CglibAOPBaseClass implements MethodInterceptor {

	private Enhancer enhancer = new Enhancer();

	protected List<Object> interMethodNames = new ArrayList<Object>();

	protected abstract void initInterMethodNames();

	public CglibAOPBaseClass() {
		this.initInterMethodNames();
	}

	public Object intercept(Object proxy, Method method, Object[] arg, MethodProxy methodProxy) throws Throwable {
		Object result = null;

		if (interMethodNames.contains(method.getName())) {
			try {
				System.out.println("代理方法执行前");
				result = methodProxy.invokeSuper(proxy, arg);
				System.out.println("代理方法执行后");
			} catch (Throwable e) {
				System.out.println("代理方法执行遇到异常");
			} finally {
				System.out.println("代理方法执行最后");
			}
		} else {
			result = methodProxy.invokeSuper(proxy, arg);
		}

		return result;
	}

	public Object bind(Class<?> clz) {
		this.enhancer.setSuperclass(clz);
		this.enhancer.setCallback(this);
		return this.enhancer.create();
	}
}
